<?php
// +----------------------------------------------------------------------
// | Bwsaas
// +----------------------------------------------------------------------
// | Copyright (c) 2015~2023 http://www.buwangyun.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Gitee ( https://gitee.com/buwangyun/bwsaas )
// +----------------------------------------------------------------------
// | Author: buwangyun <hnlg666@163.com>
// +----------------------------------------------------------------------
// | Date: 2023-06-25 10:55:00
// +----------------------------------------------------------------------

declare (strict_types = 1);

namespace buwang\command;


use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option as InputOption;
use think\console\Output;
use think\migration\command\migrate\Run;

class MigrateRunCommand extends Run
{
    //应用目录名
    protected $app_name;

    protected function configure()
    {
        // 指令配置
        $this->setName('mn-migrate:run')
            ->setDescription('Migrate the database')
            ->addArgument('app_name', Argument::REQUIRED, 'migrate the app database')
            ->addOption('--target', '-t', InputOption::VALUE_REQUIRED, 'The version number to migrate to')
            ->addOption('--date', '-d', InputOption::VALUE_REQUIRED, 'The date to migrate to')
            ->setHelp(<<<EOT
The <info>migrate:run</info> command runs all available migrations, optionally up to a specific version

<info>php think mn-migrate:run app_name</info>
<info>php think mn-migrate:run app_name -t 20230625095642</info>
<info>php think mn-migrate:run app_name -d 20230625</info>
<info>php think mn-migrate:run -v</info>

EOT
            );
    }

    protected function execute(Input $input, Output $output)
    {
        $this->app_name = strtolower($input->getArgument('app_name'));
        $version = $input->getOption('target');
        $date    = $input->getOption('date');

        // run the migrations
        try {
            $start = microtime(true);
            if (null !== $date) {
                $this->migrateToDateTime(new \DateTime($date));
            } else {
                $this->migrate($version);
            }
            $end = microtime(true);
            $this->migrations = null;
            $output->writeln("Command executed successfully ".  sprintf('%.4fs', $end - $start) . '</comment>');
        } catch (\Exception $e) {
            $output->writeln("Command failed " . $e->getMessage());
        }
    }

    /**
     * 重新设置 migration path
     * @time 20230625
     * @return string
     */
    protected function getPath(): string
    {
        return app()->getAppPath() . $this->app_name . DS. 'database' . DS. 'migrations' . DS;
    }
}
